package 队列与栈;

import java.util.Stack;

//逆波兰表达式
//https://leetcode.cn/problems/evaluate-reverse-polish-notation/description/
class 逆波兰表达式 {
    public int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<>();
        for (String token : tokens) {
            if (token.equals("+")) {
                String one = stack.pop();
                String tow = stack.pop();
                stack.push(String.valueOf(Integer.parseInt(one) + Integer.parseInt(tow)));
            } else if (token.equals("-")) {
                //减数
                String one = stack.pop();
                //被减数
                String tow = stack.pop();
                stack.push(String.valueOf(Integer.parseInt(tow) - Integer.parseInt(one)));
            } else if (token.equals("*")) {
                String one = stack.pop();
                String tow = stack.pop();
                stack.push(String.valueOf(Integer.parseInt(one) * Integer.parseInt(tow)));
            } else if (token.equals("/")) {
                String one = stack.pop();
                String tow = stack.pop();
                stack.push(String.valueOf(Integer.parseInt(tow) / Integer.parseInt(one)));
            } else {
                stack.push(token);
            }
        }
        return Integer.parseInt(stack.pop());
    }
}
/*
* 1ms
* class Solution {
    private int index;

    public int evalRPN(String[] tokens) {
        index = tokens.length - 1;
        return eval(tokens);
    }

    private int eval(String[] tokens) {
        String token = tokens[index];
        if ("+".equals(token)) {
            --index;
            int b = eval(tokens);
            --index;
            int a = eval(tokens);
            return a + b;
        } else if ("-".equals(token)) {
            --index;
            int b = eval(tokens);
            --index;
            int a = eval(tokens);
            return a - b;
        } else if ("*".equals(token)) {
            --index;
            int b = eval(tokens);
            --index;
            int a = eval(tokens);
            return a * b;
        } else if ("/".equals(token)) {
            --index;
            int b = eval(tokens);
            --index;
            int a = eval(tokens);
            return a / b;
        } else {
            return Integer.parseInt(token);
        }
    }
}
* */
